package org.dromara.xxmj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.xxmj.domain.Course;
import org.dromara.xxmj.domain.CourseOrder;
import org.dromara.xxmj.domain.dto.CourseOrderDto;
import org.dromara.xxmj.domain.vo.CourseOrderVo;
import org.dromara.xxmj.mapper.CourseMapper;
import org.dromara.xxmj.mapper.CourseOrderMapper;
import org.dromara.xxmj.service.ICourseOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 课程订单服务实现类
 *
 * @author Vincent
 */
@RequiredArgsConstructor
@Service
public class CourseOrderServiceImpl implements ICourseOrderService {

    @Resource
    private CourseOrderMapper orderMapper;

    @Resource
    private CourseMapper courseMapper;

    /**
     * 创建课程订单
     *
     * @param dto 订单信息
     * @return 订单ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(CourseOrderDto dto) {
        Long userId = LoginHelper.getUserId();
        Long courseId = dto.getCourseId();

        // 检查课程是否存在
        Course course = courseMapper.selectById(courseId);
        if (course == null) {
            throw new ServiceException("课程不存在");
        }

        // 检查课程是否已下架
        if ("1".equals(course.getStatus())) {
            throw new ServiceException("课程已下架");
        }

        // 检查用户是否已购买
        Boolean purchased = courseMapper.checkUserPurchased(userId, courseId);
        if (purchased != null && purchased) {
            throw new ServiceException("您已购买过该课程");
        }

        // 校验价格
        if (dto.getAmount().compareTo(course.getPrice()) != 0) {
            throw new ServiceException("订单金额有误");
        }

        // 创建订单
        CourseOrder order = new CourseOrder();
        order.setOrderNo(generateOrderNo());
        order.setUserId(userId);
        order.setCourseId(courseId);
        order.setAmount(dto.getAmount());
        order.setStatus("0"); // 未支付
        order.setRemark(dto.getRemark());

        if (orderMapper.insert(order) > 0) {
            return order.getId();
        }

        throw new ServiceException("创建订单失败");
    }

    /**
     * 获取订单详情
     *
     * @param id 订单ID
     * @return 订单详情
     */
    @Override
    public CourseOrder getOrderById(Long id) {
        Long userId = LoginHelper.getUserId();
        CourseOrder order = orderMapper.selectById(id);

        // 校验订单归属
        if (order == null || !userId.equals(order.getUserId())) {
            throw new ServiceException("订单不存在");
        }

        return order;
    }

    /**
     * 支付订单
     *
     * @param id 订单ID
     * @param payType 支付方式
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean payOrder(Long id, String payType) {
        Long userId = LoginHelper.getUserId();
        CourseOrder order = orderMapper.selectById(id);

        // 校验订单
        if (order == null || !userId.equals(order.getUserId())) {
            throw new ServiceException("订单不存在");
        }

        // 校验订单状态
        if (!"0".equals(order.getStatus())) {
            throw new ServiceException("订单状态不正确");
        }

        // 设置支付信息
        order.setStatus("1"); // 已支付
        order.setPayType(payType);
        order.setPayTime(new Date());

        // 更新订单
        return orderMapper.updateById(order) > 0;
    }

    /**
     * 取消订单
     *
     * @param id 订单ID
     * @return 是否成功
     */
    @Override
    public Boolean cancelOrder(Long id) {
        Long userId = LoginHelper.getUserId();
        CourseOrder order = orderMapper.selectById(id);

        // 校验订单
        if (order == null || !userId.equals(order.getUserId())) {
            throw new ServiceException("订单不存在");
        }

        // 校验订单状态
        if (!"0".equals(order.getStatus())) {
            throw new ServiceException("订单状态不正确");
        }

        // 取消订单
        order.setStatus("2"); // 已取消

        return orderMapper.updateById(order) > 0;
    }

    /**
     * 获取课程销量
     *
     * @param courseId 课程ID
     * @return 销量
     */
    @Override
    public Integer getCourseOrderCount(Long courseId) {
        return orderMapper.getCourseOrderCount(courseId);
    }

    @Override
    public List<CourseOrderVo> listOrders(PageQuery pageQuery) {
        Long userId = LoginHelper.getUserId();
        return orderMapper.listOrders(pageQuery.build(),userId);

//        QueryWrapper<CourseOrder> queryWrapper = new QueryWrapper<>();
//        return orderMapper.selectList(pageQuery.build());
//        return null;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "BYJY" + DateUtils.dateTimeNow() + StringUtils.leftPad(String.valueOf((int) (Math.random() * 10000)), 4, '0');
    }
}
